# -*- coding: utf-8 -*-
import os
import re
import json
import urllib

from base import mcLogger
from base import mcScrapper
from base import mcDown
		
class wuploadDown(mcDown):

	@classmethod
	def exist_file(self, url):
		
		out = mcScrapper.post(url)
		m = re.search('<div class="not-found" id="download-header">', out)
		if m :
			return False
		
		return True

	def login(self, cookies_file):
		
		
		#salida = mcScrapper.get("http://www.wupload.com/", cookies_file)
		
		url = "http://www.wupload.com/account/login"
	
		email = "sealcrt@hotmail.com"
		password = 'seal1980'
	
		data = {
		
		'email': email,
		'password': password,
		'redirect': '/',
		'rememberMe': '1'

		}

		headers = { 'X-Requested-With' : 'XMLHttpRequest',
					'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
					'Referer' : 'http://www.wupload.com/',
					'Accept' : 'application/json, text/javascript, */*; q=0.01',
					'Host' : 'www.wupload.com'					
					}

		post = urllib.urlencode(data)		
		salida = mcScrapper.post(url, post, cookies_file, headers)
		
		
		js = json.loads(salida)
		
		if js['status']=='success':
			return True
			
		return False
		
	def down(self, url, output_file, cookies_file):
		
			mcScrapper.down( url, cookies_file, None , output_file)
			#os.system("curl -w '%{http_code}' --fail --globoff -o 'salida.mp4' '" + m.group(1) + "' ")
			print "Download Success"
			return True
		
	def run(self, url, output_file):
		
		print "Wupload\n"
		logger = mcLogger.getInstance('wupload')

		cookies_file = "cookies/wupload"

		os.system("rm -f " + cookies_file)

		url=url[:url.find("?")-1]

		sid=""
		m = re.search("file/(.*)", url)
		if m :
			sid=m.group(1)

		url_base = url
		url = url_base + "/"+ sid +"?start=1"

		print url


		#Login
		if self.login(cookies_file):
			print "Login Succefull"
			self.down(url, output_file, cookies_file)
			return
		else:
			print "Login Failed"


		salida = mcScrapper.get(url, cookies_file, { 'X-Requested-With': 'XMLHttpRequest', 'Referer': url_base, "Set-Cookie": "isJavascriptEnable=1", "Set-Cookie": "lastUrlLinkId="+sid  })

		print salida

		m = re.search('File does not exist', salida)
		if m :  
			print "File Removed"
			return False


		#-------
		# WAIT
		#-------
		m = re.search('id="freeUserDelay"', salida)
		if m :  
			tm = ""
			tm_hash = ""
			wait=""
			
			m1 = re.search("id='tm' name='[^']*' value='([^']*)", salida)
			if m1:
			  tm = m1.group(1)

			m2 = re.search("id='tm_hash' name='[^']*' value='([^']*)", salida)
			if m2:
			  tm_hash = m2.group(1)

			m3 = re.search(	'countDownDelay = ([0-9]*);', salida)
			if m3:
			  wait = m3.group(1)

			self.wait(wait)
			
			data = {

			'tm': tm,
			'tm_hash': tm_hash

			}

			post = urllib.urlencode(data)
			salida = mcScrapper.post(url, post, cookies_file, {'X-Requested-With': 'XMLHttpRequest', 'Referer': url_base })

		#--------
		# CAPTCHA
		#--------
		m = re.search("Please enter the captcha below", salida)
		if m:
			print "Captcha\n"			
			post =  mcDown.reCaptcha( "6LdNWbsSAAAAAIMksu-X7f5VgYy8bZiiJzlP83Rl", cookies_file)
			#
			headers =  { 'X-Requested-With': 'XMLHttpRequest', 'Referer': url_base , 'Content-Type' : 'application/x-www-form-urlencoded'}
			salida = mcScrapper.request(url_base, post, cookies_file, headers)
			
			print salida['url']
			print salida['str']
			
			return
		
		#-----
		#READY
		#-----
		m = re.search('Download Ready', salida)
		if m:

			print "Download Ready\n"
			m = re.search('Download Ready[^>]*>[^>]*>[^>]*><a href=\"([^\"]*)', salida)
			url = m.group(1)
			print "Link: " + url

			return self.down(url, output_file, cookies_file)
			

		print "Some error"
		return False	

	